#!/bin/bash
#
# This is a sample thinkpad key handler from openSUSE.
# In openSUSE, there is a file called thinkpad in /etc/acpi/events.
# It directs all thinkpad hotkeys to /usr/lib/acpid/thinkpad_handler,
# this file's original version. This file will process the keys and
# act on them. In volume/brightness case, the trick was to first
# call 'xauth +localhost', then set XAUTHORITY environment variable
# for the call to showvolumebrightness -application. All this was
# needed since this script is run as root, and root doesn't have
# an existing X session.
#
HOTKEY=$1
set $HOTKEY
EVENT=$1   # "ibm/hotkey"
ACPI=$2    # "HOTK"
WHAT=$3    # "00000080"
SERIAL=$4  # "0000100c" Fn+F12

UID_AT_CONSOLE=$(who|head -1|cut -d' ' -f1)

function ShowCommand {
  DISPLAY=:0.0 XAUTHORITY=/home/$UID_AT_CONSOLE/.Xauthority /usr/bin/showvolumebrightness $1 &
}

# bluetooth
if [ "$WHAT" = "00000080" ]; then
    case "$SERIAL" in
        # bluetooth
        "00001005")
        ACTION="disable"
        grep -q "disabled" "/proc/acpi/ibm/bluetooth" && ACTION="enable"
        echo $ACTION > "/proc/acpi/ibm/bluetooth"
        ;;
        # sleep
        "00001004")
        export DBUS_SESSION_BUS_ADDRESS=$(cat /proc/$(pgrep kded4|sort|head -1)/environ | tr '\0' '\n' | grep DBUS_SESSION_BUS_ADDRESS | cut -d '=' -f2-)
        su -c "qdbus org.freedesktop.PowerManagement /org/freedesktop/PowerManagement Suspend" $UID_AT_CONSOLE
        ;;
        # brightness up/down
        "00001010" | "00001011")
        STATUS_TYPE="brightness"
        ShowCommand brightness
        ;;
        # volume up/down/mute
        "00001015" | "00001016" | "00001017")
        ShowCommand volume
        ;;
    esac
fi
